package net.code;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;


public class Encoder implements ProtocolEncoder {
	private final AttributeKey DEFLATER = new AttributeKey(getClass(), "deflater");
	private static final int cachesize = 1024;

	public void dispose(IoSession arg0) throws Exception {
		// TODO Auto-generated method stub

	}

	public void encode(IoSession arg0, Object arg1, ProtocolEncoderOutput arg2) throws Exception {
		String s = (String) arg1;
		byte[] bytes = s.getBytes("utf8");
		bytes = compress(arg0, bytes);
		IoBuffer bb = IoBuffer.allocate(bytes.length + 4, false);
		bb.putInt(bytes.length);
		bb.put(bytes);
		bb.flip();
		arg2.write(bb);
		arg2.flush();
		bb.free();
	}

	private byte[] compress(IoSession session, byte[] inputs) {
		Deflater deflater = (Deflater) session.getAttribute(DEFLATER);
		if (deflater == null) {
			deflater = new Deflater();
			session.setAttribute(DEFLATER, deflater);
		}

		deflater.reset();
		deflater.setInput(inputs);
		deflater.finish();
		byte outputs[] = new byte[0];
		ByteArrayOutputStream stream = new ByteArrayOutputStream(inputs.length);
		byte[] bytes = new byte[cachesize];
		int value;
		while (!deflater.finished()) {
			value = deflater.deflate(bytes);
			stream.write(bytes, 0, value);
		}

		outputs = stream.toByteArray();
		try {
			stream.close();
		} catch (IOException e) {
			// MyPrint.print(ExceptionUtils.getFullStackTrace(e));
		}

		return outputs;
	}

}
